// store数据
import { useCounterStore } from "@/stores/index.js";
import NProgress from 'nprogress'; // 进度条
import 'nprogress/nprogress.css'; // 进度条样式
// Layout
import Layout from '@/components/Layout/index.vue'
// 菜单数据
import menuList from "@/components/Layout/menu.js";
NProgress.configure ({showSpinner: false});
// 白名单
const whiteList = ['/login'];
// 识别views下的所有vue文件
const modules = import.meta.glob('../views/**/*.vue')
const menuToroute = (routes,type="first")=>{
  if (!routes) return
  return routes.map(item => {
    const pathSplit = item.path.split('/')
  
    if(type === 'first'){
      item.path = '/'+pathSplit[pathSplit.length - 1]
      item.component = Layout
      if(item.children){
        menuToroute(item.children,'nofirst')
      }else{
      item.children = [{
        path:'index',
        component:modules[`../${item.view}`],
        meta:{
          title:item.title,
          icon:item.icon
        }
      }]
      }
    }else{
      item.path = pathSplit[pathSplit.length - 1]
      item.meta = {
        icon:'',
        title:item.title
      }
      if(item.children && item.children.length>0){
        // item.component = Layout
        menuToroute(item.children,'nofirst')
      }else{
        item.component = modules[`../${item.view}`]
      }
    }
    return item
  })
}

// 设置动态路由(必须以404结尾)
export async function setAddRoute(router,store) {
  let DTrouters =  await menuToroute(JSON.parse(JSON.stringify(menuList.list)))
  console.log('DTrouters')
  console.log(DTrouters)
  DTrouters.forEach((item)=>{
    console.log(item)
    router.addRoute(item)
  })
  router.addRoute(
    { path: "/:cachAlll(.*)", redirect: "/404", hidden: true }
  )
  // 设置当前状态为已经添加动态路由
  store.setMenuAuto()
}
export function setupPermission (router) {
  // 全局路由钩子
  router.beforeEach (async (to, from, next) => {
    console.log(to)
    // store数据
    const store = useCounterStore();
    // 取消跳转之前请求的接口请求
    store.clearCancleToken();
    // 开始进度条
    NProgress.start ();
    // 设置页面标题
    document.title = to.meta.title;
    // 判断当前是否有Token
    if (store.token) {
      if (to.path === '/login') {
        // 如果已有token 即使是登录页也跳转首页
        next ({
          path: '/recharge',
        });
        NProgress.done ();
      } else {
        // **store.menurouteState(表示是否已经加载了动态路由)
        if (store.menurouteState) {
          console.log('next')
          next()
        } else {
          // 添加动态路由后 
          // next({...to,replace:true}) 意思是强制重新导航并且替换历史记录(应用场景就是动态路由添加后更新路由表)
          await setAddRoute(router,store)
          console.log('next to')
           next ({
            ...to,
            replace: true,
          });
        }
      }
    } else {
      // 无token情况
      if (whiteList.indexOf (to.path) !== -1) {
        // 如果在白名单 继续执行
        next ();
      } else {
        // 不在白名单中则跳转登录
        next (`/login?redirect=${to.path}`);
        NProgress.done ();
      }
    }
  });
  router.afterEach (() => {
    // 加载结束
    NProgress.done ();
  });
}
